﻿using AddressBooks.Entities;
using AddressBooks.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Collections;
using HandyControl.Controls;
using NetTaste;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace AddressBooks.ViewModel;

partial class ContactsRefreshViewModel : ObservableObject
{
    public ManualObservableCollection<PublicContacts> DataList { get; set; } = new();
    /// <summary>
    /// 触发重新生成单位ID命令
    /// </summary>
    [RelayCommand]
    private async Task RecountOrgId()
    {
        try
        {
            bool ok = await orgManager.RecountOrgId(null);
            Growl.Info(ok ? "操作成功" : "无内容更新");
        }
        catch (Exception)
        {
            Growl.Error("生成ID出错");
        };
    }
    /// <summary>
    /// 更新通讯录里的单位代码
    /// </summary>
    /// //<Button Content = "刷新单位代码" Style="{StaticResource ButtonWarning}"/>
    [RelayCommand]
    private async Task UpdateOrgid()
    {
        try
        {
            var i = await ContactsManager.UpdateOrgId();
            Growl.Info($"更新通讯录中 {i} 条记录");
        }
        catch (Exception)
        {
            Growl.Error("更新单位代码失败");
        }
    }

    /// <summary>
    /// 根据分页和查询条件查询，请求数据
    /// </summary>
    /// <returns></returns>
    public async Task GetData()
    {
        var res = await contactsManager.AsQueryable().OrderByDescending(it => it.Uptime)
            .ToPageListAsync(pageInfo.CurrentPageIndex++, pageInfo.Limit);
        DataList.CanNotify = false;
        res?.ForEach(o => DataList.Add(o));
        DataList.CanNotify = true;

    }
    readonly OrgManager orgManager = new();
    readonly PublicContactsManager contactsManager = new();
    private PageInfo pageInfo = new() { CurrentPageIndex = 1, Limit = 20 };

    public ContactsRefreshViewModel()
    {
        _ = GetData();
    }
}
